class SingleTon:
    instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = super().__new__(cls)
        return cls.instance


def singleton(cls):
    instance = {}

    def inner(*args, **kwargs):
        if cls not in instance:
            obj = cls(*args, **kwargs)
            instance[cls] = obj
        return instance[cls]
    return inner


def singleton2(cls):
    def inner(*args, **kwargs):
        if not hasattr(cls, "__instance"):
            obj = cls(*args, **kwargs)
            setattr(cls, "__instance", obj)
        return getattr(cls, "__instance")
    return inner


@singleton
class A:
    pass


@singleton2
class B:
    pass


class SingleTonMetaclass(type):
    instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in SingleTonMetaclass.instance:
            obj = super().__call__(*args, **kwargs)
            SingleTonMetaclass.instance[cls] = obj
        return SingleTonMetaclass.instance[cls]


class C(metaclass=SingleTonMetaclass):
    pass


# new方法
a = SingleTon()
b = SingleTon()
print(a is b)

# 装饰器1
p1 = A()
p2 = A()
print(p1 is p2)

# 装饰器2
c1 = B()
c2 = B()
print(c1 is c2)

# 元类
d1 = C()
d2 = C()
print(d1 is d2)
